module(..., package.seeall)

function new(obj)
	local ui = require("ui")

	local menuGroup = display.newGroup()
	local tapSound = audio.loadSound( "tapsound.wav" )
	local tangtoc = audio.loadStream("audios/tangtoc.mp3" )
	local tt30s = audio.loadStream("audios/tt30s.mp3" )
	
	local times 				= 60
	local score 				= obj.score
	local quesAnswer 			= 0
	---------------------------------------------
	--
	---------------------------------------------
	local dataTangToc = obj.dataTangToc
	---------------------------------------------
	--
	---------------------------------------------
	function displayFinish()
		--Hien thong bao het thoi gian phan thi
		if groupResult == nil then
			groupResult = display.newGroup()
			groupKhoiDong:insert(groupResult)		
			
			bgMessage = display.newImage("images/bgMessage.png")
			bgMessage.x = display.contentWidth/2
			bgMessage.y = display.contentHeight/2
			groupResult:insert(bgMessage)
			
			yy = bgMessage.y - bgMessage.height/2 + 40
			displayText(200, groupResult, "BẠN ĐÃ HOÀN THÀNH PHẦN THI TĂNG TỐC", bgMessage.x - bgMessage.width/2 + 26, yy, bgMessage.width - 20, 16, 0, 0, 255)
			
			yy = bgMessage.y - 32
			displayText(500, groupResult, "XIN CHÚC MỪNG BẠN", bgMessage.x - bgMessage.width/2 + 68, yy, bgMessage.width - 20, 18, 0, 0, 255)
			
			yy = bgMessage.y
			displayText(500, groupResult, "ĐÃ DÀNH ĐƯỢC " .. score .. " ĐIỂM", bgMessage.x - bgMessage.width/2 + 58, yy, bgMessage.width - 20, 18, 0, 0, 255)
						
			btnDiTiep = ui.newMyButton{
			default = "images/btnDiTiep.png",
			over = "images/btnDiTiepOver.png",
				onRelease = function(event)
					--Tro ve man hinh truoc
					timer.performWithDelay(100, function(event)
						--luu diem so man choi de sang man tiep theo
						obj.score  = score
						director:changeScene("vedich", obj)
					end, 1)
				end
			}
			btnDiTiep.x = bgMessage.x
			btnDiTiep.y = bgMessage.y + 52
			btnDiTiep.isVisible = false
			groupResult:insert(btnDiTiep)
			
			timer.performWithDelay(1000, function(e)
				btnDiTiep.isVisible = true
				--Luu diem so len server
				timer.performWithDelay(200, submitAccountScore, 1)
			end, 1)
		end
	end
	---------------------------------------------
	--
	---------------------------------------------
	function dispayAccont()
		if fullNameText == nil then
			fullNameText = display.newText("Trần Anh Tuấn", 112,  122, "Helvetica", 12)
			fullNameText:setTextColor(255, 255, 255)
			fullNameText.x = 112
			fullNameText.align = "center"
			menuGroup:insert( fullNameText )	
		else
			fullNameText.text = "Trần Anh Tuấn"
		end
		
		if quesAllText == nil then
			quesAllText = display.newText("12 câu hỏi", 280,  122, "Helvetica", 12)
			quesAllText:setTextColor(255, 0, 0)
			quesAllText.x = 280
			quesAllText.align = "center"
			menuGroup:insert( quesAllText )	
		else
			quesAllText.text = "Bộ 12 câu"
		end
	end
	---------------------------------------------
	--
	---------------------------------------------
	function slipWords(str, key)
		local k = 1
		local index = 1
		local data = {}
		while index > 0 do
			local i, j = string.find(str, key, k)
			if i == nil then
				data[index] = str:sub(k)
				--print(data[index])
				index = -1
			else
				--print(i .. " - " .. j)
				local si = str:sub(k, i - 1)
				data[index] = si
				--print(data[index])
				k = j + 1
			end
			index = index + 1
		end
		return data
	end
	---------------------------------------------
	--Hien thi cau hoi tu hang nang
	---------------------------------------------
	function showQuestions(contents, answers, answerABCD)
						
		local AX = nil
		local BX = nil
		local CX = nil
		local DX = nil
			
		local groupQuestion = nil
		if groupQuestion == nil then
			groupQuestion = display.newGroup()
			groupQuestion.isVisible = false
			menuGroup:insert(groupQuestion)
			
			bgtangtoc = display.newImage("images/bgtangtoc.png")
			bgtangtoc.x = bgtangtoc.width/2
			bgtangtoc.y = bgtangtoc.height/2
			groupQuestion:insert(bgtangtoc)
		end
		
		if groupQuestion.isVisible == false then
			groupQuestion.isVisible = true
			groupQuestion.xScale = 0.2
			groupQuestion.yScale = 0.2

			transition.to(groupQuestion, {time=1500, xScale = 1, yScale = 1, transition=easing.outExpo,
				onComplete = function(event) 
					--Su kien slide khung hien thi cau hoi da thuc hien xong
					xx = bgtangtoc.x - bgtangtoc.width/2 + 100
					yy = bgtangtoc.y - bgtangtoc.height/2 + 72;
					displayText(200, groupQuestion, contents, xx, yy, 250, 14, 0, 0, 255)
					displayText(2000, groupQuestion, answers, xx,  bgtangtoc.y + bgtangtoc.height/2 - 40, 250, 14, 0, 0, 255)
				end})

			A = ui.newMyButton{
			default = "images/A.png",
			over = "images/AX.png",
				onRelease = function(event)
					if times > 0 and AX == nil then
						AX = display.newImage("images/AX.png")
						AX.x = A.x
						AX.y = A.y
						groupQuestion:insert(AX)	
						--Ghi nhan thoi gian tra loi
						AX.times = 30 - times

						if BX then
							BX:removeSelf()
							BX = nil
						end
						if CX then
							CX:removeSelf()
							CX = nil
						end
						if DX then
							DX:removeSelf()
							DX = nil
						end
					end
				end
			}
			A.x = 50
			A.y = 290
			groupQuestion:insert(A)	
			
			B = ui.newMyButton{
			default = "images/B.png",
			over = "images/BX.png",
				onRelease = function(event)
					if times > 0 and BX == nil then
						BX = display.newImage("images/BX.png")
						BX.x = B.x
						BX.y = B.y
						groupQuestion:insert(BX)	
						--Ghi nhan thoi gian tra loi
						BX.times = 30 - times

						if AX then
							AX:removeSelf()
							AX = nil
						end
						if CX then
							CX:removeSelf()
							CX = nil
						end
						if DX then
							DX:removeSelf()
							DX = nil
						end
					end
				end
			}
			B.x = 120
			B.y = 290
			groupQuestion:insert(B)	
			
			C = ui.newMyButton{
			default = "images/C.png",
			over = "images/CX.png",
				onRelease = function(event)
					if times > 0 and CX == nil then
						CX = display.newImage("images/CX.png")
						CX.x = C.x
						CX.y = C.y
						groupQuestion:insert(CX)	
						--Ghi nhan thoi gian tra loi
						CX.times = 30 - times
						
						if AX then
							AX:removeSelf()
							AX = nil
						end
						if BX then
							BX:removeSelf()
							BX = nil
						end
						if DX then
							DX:removeSelf()
							DX = nil
						end
					end
				end
			}
			C.x = 120 + 70
			C.y = 290
			groupQuestion:insert(C)	
			
			D = ui.newMyButton{
			default = "images/D.png",
			over = "images/DX.png",
				onRelease = function(event)
					if times > 0 and DX == nil then
						DX = display.newImage("images/DX.png")
						DX.x = D.x
						DX.y = D.y
						groupQuestion:insert(DX)	
						--Ghi nhan thoi gian tra loi
						DX.times = 30 - times

						if AX then
							AX:removeSelf()
							AX = nil
						end
						if BX then
							BX:removeSelf()
							BX = nil
						end
						if CX then
							CX:removeSelf()
							CX = nil
						end
					end
				end
			}
			D.x = 120 + 2*70
			D.y = 290
			groupQuestion:insert(D)	
		end

		function begin()
			if times > 0 then
				times = times - 1
				showScore()
				
				if nut then
					k = 130/30
					nut.y = 68 + k*(30 - times)
					nut:toFront()
				end
			end
			if times == 0 then
				local groupAnswerTangToc = nil
				local myAnswerABCD = ""
				local myTimeIndex = 0
				if groupAnswerTangToc == nil then
					groupQuestion.isVisible = false
					groupAnswerTangToc = display.newGroup()
					menuGroup:insert(groupAnswerTangToc)
					
					bganswertangtoc = display.newImage("images/bganswertangtoc.png")
					bganswertangtoc.x = display.contentWidth/2
					bganswertangtoc.y = -100
					groupAnswerTangToc:insert(bganswertangtoc)
					
					transition.to(bganswertangtoc, {time=1000, x = display.contentWidth/2, y = display.contentHeight/2,
						onComplete = function(event) 
							local myTimes = 60
							myAnswerABCD = ""
							if AX then
								myTimes = AX.times
								myAnswerABCD = "A"
							end
							if BX then
								myTimes = BX.times
								myAnswerABCD = "B"
							end
							if CX then
								myTimes = CX.times
								myAnswerABCD = "C"
							end
							if DX then
								myTimes = DX.times
								myAnswerABCD = "D"
							end
							--print("quesAnswer: " .. quesAnswer)
							dataTangToc[quesAnswer].members[4] = {}
							dataTangToc[quesAnswer].members[4].fullname = obj.fullname
							dataTangToc[quesAnswer].members[4].answerABCD = myAnswerABCD
							dataTangToc[quesAnswer].members[4].times = myTimes
							dataTangToc[quesAnswer].members[4].email = obj.email
							
							--xoa phan cau hoi
							cleanGroups(groupQuestion, 0)

							local j = 1
							while j < 5 do
								local member = nil
								local i = 1
								local ii = -1
								while(i < 5) do
									if (member == nil or myTimes > dataTangToc[quesAnswer].members[i].times) and dataTangToc[quesAnswer].members[i].show == nil then
										member = dataTangToc[quesAnswer].members[i]
										ii = i
										myTimes = dataTangToc[quesAnswer].members[i].times
									end
									i = i + 1
								end
								if member then
									member = dataTangToc[quesAnswer].members[ii]
									dataTangToc[quesAnswer].members[ii].show = true
									
									iText = display.newText(member.answerABCD, display.contentWidth/2 - (3-j)*20, (bganswertangtoc.y - bganswertangtoc.height/2 + 26) + (j-1)*59, "Helvetica", 24)
									iText:setTextColor(255, 255, 0)
									iText.align = "center"
									groupAnswerTangToc:insert( iText )
									
									iText = display.newText(member.times, display.contentWidth/2 - (3-j)*20 - 64, (bganswertangtoc.y - bganswertangtoc.height/2 + 26) + (j-1)*59 - 12, "Helvetica", 10)
									iText:setTextColor(255, 255, 0)
									iText.align = "center"
									groupAnswerTangToc:insert( iText )
									
									iText = display.newText(member.fullname, display.contentWidth/2 - (3-j)*20 + 64, (bganswertangtoc.y - bganswertangtoc.height/2 + 26) + (j-1)*59 - 12, "Helvetica", 10)
									iText:setTextColor(255, 255, 0)
									iText.align = "center"
									iText.x = display.contentWidth/2 - (3-j)*20 + 132 - iText.width/2
									groupAnswerTangToc:insert( iText )
								end
								--ghi nhan vi thu tra loi cau hoi cua nguoi choi
								if member and member.email == obj.email then
									myTimeIndex = 1
									local k = 1
									while k < 5 do
										if dataTangToc[quesAnswer].members[k].times < myTimes and dataTangToc[quesAnswer].members[k].answerABCD == dataTangToc[quesAnswer].answerABCD then
											myTimeIndex = myTimeIndex + 1
										end
										k = k + 1
									end
								end
								
								j = j + 1
								myTimes = 60
							end
							timer.performWithDelay(2500, function(event)
								answerABCD = display.newImage("images/" .. dataTangToc[quesAnswer].answerABCD .. ".png")
								answerABCD.x = display.contentWidth/2
								answerABCD.y = display.contentHeight - answerABCD.height/2 - 1
								groupAnswerTangToc:insert(answerABCD)

								timer.performWithDelay(200, function(event)
									if answerABCD.xScale == 1 then
										answerABCD.xScale = 0.7
										answerABCD.yScale = 0.8
									else
										answerABCD.xScale = 1
										answerABCD.yScale = 1
									end
								end, 20)		
							end, 1)
							timer.performWithDelay(8000, function(event)
								print(myAnswerABCD)
								if myTimeIndex > 0 and dataTangToc[quesAnswer].answerABCD == myAnswerABCD then
									score = score + (5-myTimeIndex)*10
									showScore()
								end
								--xoa phan cau hoi
								cleanGroups(groupAnswerTangToc, 0)
								--Hien thi cau hoi tiep theo
								if quesAnswer < 4 then
									times = 60
									quesAnswer = quesAnswer + 1
									showQuestions(dataTangToc[quesAnswer].questions, dataTangToc[quesAnswer].answers, dataTangToc[quesAnswer].answerABCD)
								else
									displayFinish()
								end
							end, 1)
						end})
				end
			end
		end
		audio.stop()
		--dat thoi gian phan thi la 60 giay
		times = 30
		--bat dau tinh thoi gian phan thi
		timer.performWithDelay(4000, function(event)
			timer.performWithDelay(1000, begin, 30)
			audio.play( tt30s, { channel=1, loops=0, fadein=5000})
		end, 1)
	end
	---------------------------------------------
	--Hien thi diem so va thoi gian tra loi cau hoi
	---------------------------------------------
	function showScore()
		if scoreGroup == nil then
			scoreGroup = display.newGroup()

			bgscore = display.newImage("images/bgscore.png")
			bgscore.x = display.contentWidth - bgscore.width/2
			bgscore.y = display.contentHeight - bgscore.height/2
			
			scoreGroup:insert(bgscore)
			menuGroup:insert(scoreGroup)
		end
		
		if scoreText == nil then
			scoreText = display.newText( "" .. score, 370,  286, "Helvetica", 24)
			scoreText:setTextColor(255, 255, 0)
			scoreText.align = "center"
			scoreGroup:insert( scoreText )	
			
			scoreText.x = bgscore.x + scoreText.width/12
			scoreText.y = bgscore.y + scoreText.height/3
		else
			scoreText.text = "" .. score
		end
		
		if quesText == nil then
			quesText = display.newText("" .. quesAnswer, 370,  246, "Helvetica", 14)
			quesText:setTextColor(255, 0, 0)
			quesText.align = "center"
			scoreGroup:insert( quesText )	
			
			quesText.x = 370
			quesText.y = 246
			quesText.x = bgscore.x + quesText.width/12
			quesText.y = bgscore.y - bgscore.height/2 + quesText.height - 4
		else
			quesText.text = "" .. quesAnswer
		end
		
		if nut == nil then
			nut = display.newImage("images/nut2.png")
			menuGroup:insert( nut )	
			
			nut.x = 48
			nut.y = 40
		end
	end
	---------------------------------------------
	--
	---------------------------------------------
	function displayText(delay, group, str, xx, yy, width, fontSize, r, g, b)
		timer.performWithDelay(delay, function(event)
			local words = slipWords(str, ' ')
			local i = 1
			local x = xx
			local y = yy
			while i < #words + 1 do
				local word = display.newText(words[i], 0, 0, native.systemFontBold, fontSize)
				word:setTextColor(r, g, b)
				group:insert(word)
				
				if x + word.width < (xx + width) then
					xxy = x + word.width/2
					yyy = y
					
					word.x = 480
					word.y = 320
					--Hieu ung bay chu tu goc duoi ben trai
					transition.to(word, {time=100*i, x = xxy, y = yyy})
					
					x = x + word.width  + 3
				else
					y = y + 20
					x = xx
					
					xxy = x + word.width/2
					yyy = y
					
					word.x = 480
					word.y = 320
					--Hieu ung bay chu tu goc duoi ben trai
					transition.to(word, {time=100*i, x = xxy, y = yyy})
					
					x = x + word.width  + 3
				end
				i = i+1
			end
		end, 1)
		return y
	end
	---------------------------------------------
	--
	---------------------------------------------
	function start()
		if groupQuestionStart == nil then
			groupQuestionStart = display.newGroup()
			menuGroup:insert(groupQuestionStart)		
			
			bgMessage = display.newImage("images/bgMessage.png")
			bgMessage.x = display.contentWidth/2
			bgMessage.y = display.contentHeight/2
			groupQuestionStart:insert(bgMessage)
			
			yy = bgMessage.y - bgMessage.height/2 + 40
		    displayText(200, groupQuestionStart, "OLYMPIA TRÊN MOBILE", bgMessage.x - bgMessage.width/2 + 75, yy, bgMessage.width - 20, 16, 0, 0, 255)
			
			yy = bgMessage.y - 32
			displayText(500, groupQuestionStart, "PHẦN THI TĂNG TỐC", bgMessage.x - bgMessage.width/2 + 68, yy, bgMessage.width - 20, 20, 0, 0, 255)
			
			
			btnStart = ui.newMyButton{
			default = "images/btnSanSang.png",
			over = "images/btnSanSangOver.png",
				onRelease = function(event)
					--xoa giao dien thong bao
					cleanGroups(groupQuestionStart, 0)
					quesAnswer = 1
					showQuestions(dataTangToc[quesAnswer].questions, dataTangToc[quesAnswer].answers, dataTangToc[quesAnswer].answerABCD)
				end
			}
			btnStart.x = bgMessage.x
			btnStart.y = bgMessage.y + 52
			groupQuestionStart:insert(btnStart)
			
			--nghe gioi thieu 60 giay va tu dao vao phan thi sau do
			--[[audio.play( tangtoc, { channel=1, loops=0, fadein=5000, onComplete = function(event) 
				if groupQuestionStart then
					--timer.performWithDelay(2000, submitAccount, 1)
					--xoa giao dien thong bao
					cleanGroups(groupQuestionStart, 0)
					quesAnswer = 1
					showQuestions(dataTangToc[quesAnswer].questions, dataTangToc[quesAnswer].answers, dataTangToc[quesAnswer].answerABCD)
				end
			end})--]]
		end
	end
	---------------------------------------------
	--init screen
	---------------------------------------------
	function drawScreen()
		
		bg = display.newImageRect("images/bg.png", display.contentWidth, display.contentHeight)
		bg.x = display.contentWidth/2
		bg.y = display.contentHeight/2
		menuGroup:insert(bg)

		start()
	end
	
	--Init gameplay screen
	drawScreen()
	---------------------------------------------
	--xoa du lieu
	---------------------------------------------
	function cleanGroups (curGroup, level)
		if curGroup.numChildren then
			while curGroup.numChildren > 0 do
				cleanGroups (curGroup[curGroup.numChildren], level+1)
			end
			if level > 0 then
				curGroup:removeSelf()
				curGroup = nil
			end
		else
			curGroup:removeSelf()
			curGroup = nil
			return
		end
	end
	
	unloadMe = function()
	end
	return menuGroup
end